//
//  GTListLoader.swift
//  headline-Swfit
//
//  Created by 大土豆 on 2019/8/23.
//  Copyright © 2019 Mac. All rights reserved.
//

import Foundation

class GTListLoader: NSObject {
    
    //NSArray转Array，主要是Array这边有完整的泛型
    func loadListDataWithFinishBlock(callback:@escaping (Bool,Array<GTListitem>) -> Void){
        let listdata = readDataFromLocal()
        if listdata.count>0 {
            NSLog("本地有值")
            callback(true, listdata);
        }
        let urlString = "https://static001.geekbang.org/univer/classes/ios_dev/lession/45/toutiao.json"
        AFHTTPSessionManager.init().get(urlString, parameters: nil, progress: nil, success: {
            (task: URLSessionTask,responObj : Any?) -> Void in
            let result = (responObj as! NSDictionary)["result"]
            let dataArray = ((result as! NSDictionary)["data"]) as! NSArray
            let array = NSArray.yy_modelArray(with: GTListitem.self, json: dataArray) as! Array<GTListitem>
            self.archiveListDataWithArray(array: array)
            callback(true,array)
        }, failure: {
            (task: URLSessionTask?,error : Error) -> Void in
            NSLog("网络访问错误")
        })
        
    }
    
    //归档这边API变动很大，得注意
    private func readDataFromLocal() -> Array<GTListitem>{
        //注意：这边Swift和Objective-c的api不一样
        let pathArray = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let cachePath = pathArray.first
        let listDataPath = NSURL(fileURLWithPath: cachePath!).appendingPathComponent("GTData/list")
        
        let readListData = FileManager.default.contents(atPath: listDataPath!.path)
        //这边接口还是没有泛型，得用强转
        if(readListData == nil){
            return Array<GTListitem>()
        }
        let unarchiveObj = NSKeyedUnarchiver.unarchiveObject(with: readListData!)
        return unarchiveObj as! Array<GTListitem>
    }
    
    private func archiveListDataWithArray(array : Array<GTListitem>){
        let pathArray = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let cachePath = pathArray.first
        
        //创建文件夹
        do{
            let dataPath = NSURL(fileURLWithPath: cachePath!).appendingPathComponent("GTData")
            try FileManager.default.createDirectory(atPath: dataPath!.path, withIntermediateDirectories: true, attributes: nil)
            let listdataPath = NSURL(fileURLWithPath: dataPath!.path).appendingPathComponent("list")
            let listdata = try NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: true)
            FileManager.default.createFile(atPath: listdataPath!.path, contents: listdata, attributes: nil)
        }catch let error{
            print("error >>> \(error)")
        }
    
    }
    
}
